const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');

// Load environment variables
dotenv.config({ path: path.join(__dirname, '..', 'backend', '.env') });

// Backup directory
const BACKUP_DIR = path.join(__dirname, '..', 'backups');

// Log file
const LOG_FILE = path.join(BACKUP_DIR, 'backup.log');

/**
 * Check backup status
 */
function checkBackupStatus() {
  console.log('=== FinanceApp Backup Status ===');
  
  // Check if backup directory exists
  if (!fs.existsSync(BACKUP_DIR)) {
    console.log('❌ Backup directory not found');
    return;
  }
  
  console.log('✅ Backup directory exists');
  
  // List backup files
  const backups = fs.readdirSync(BACKUP_DIR)
    .filter(file => file.startsWith('financeapp_backup_') && file.endsWith('.sql'))
    .map(file => {
      const stats = fs.statSync(path.join(BACKUP_DIR, file));
      return {
        file,
        size: stats.size,
        modified: stats.mtime
      };
    })
    .sort((a, b) => b.modified - a.modified);
  
  console.log(`\n📊 Total backups: ${backups.length}`);
  
  if (backups.length > 0) {
    // Show latest backup
    const latestBackup = backups[0];
    const sizeMB = (latestBackup.size / (1024 * 1024)).toFixed(2);
    const ageHours = Math.floor((Date.now() - latestBackup.modified) / (1000 * 60 * 60));
    
    console.log(`\n⏱️ Latest backup:`);
    console.log(`   File: ${latestBackup.file}`);
    console.log(`   Size: ${sizeMB} MB`);
    console.log(`   Age: ${ageHours} hours ago`);
    
    // Check if backup is recent (less than 24 hours)
    if (ageHours < 24) {
      console.log('✅ Latest backup is recent');
    } else {
      console.log('⚠️ Latest backup is older than 24 hours');
    }
    
    // Show backup history
    console.log(`\n📚 Backup history (last 5):`);
    const recentBackups = backups.slice(0, 5);
    recentBackups.forEach((backup, index) => {
      const sizeMB = (backup.size / (1024 * 1024)).toFixed(2);
      const dateStr = backup.modified.toISOString().split('T')[0];
      console.log(`   ${index + 1}. ${backup.file} (${sizeMB} MB, ${dateStr})`);
    });
  }
  
  // Check log file
  if (fs.existsSync(LOG_FILE)) {
    const logStats = fs.statSync(LOG_FILE);
    const logSizeMB = (logStats.size / (1024 * 1024)).toFixed(2);
    console.log(`\n📝 Log file: ${LOG_FILE} (${logSizeMB} MB)`);
    
    // Show last 10 lines of log
    const logContent = fs.readFileSync(LOG_FILE, 'utf8');
    const logLines = logContent.split('\n').filter(line => line.trim() !== '').slice(-10);
    console.log('\n📋 Recent log entries:');
    logLines.forEach(line => {
      console.log(`   ${line}`);
    });
  } else {
    console.log('\n📝 Log file not found');
  }
  
  console.log('\n=== End Backup Status ===');
}

/**
 * Send alert if backup is missing or failed
 */
function sendAlert() {
  // Check if backup directory exists
  if (!fs.existsSync(BACKUP_DIR)) {
    console.log('🚨 ALERT: Backup directory not found!');
    return;
  }
  
  // Check latest backup
  const backups = fs.readdirSync(BACKUP_DIR)
    .filter(file => file.startsWith('financeapp_backup_') && file.endsWith('.sql'))
    .map(file => {
      const stats = fs.statSync(path.join(BACKUP_DIR, file));
      return {
        file,
        size: stats.size,
        modified: stats.mtime
      };
    })
    .sort((a, b) => b.modified - a.modified);
  
  if (backups.length === 0) {
    console.log('🚨 ALERT: No backups found!');
    return;
  }
  
  // Check if latest backup is older than 24 hours
  const latestBackup = backups[0];
  const ageHours = Math.floor((Date.now() - latestBackup.modified) / (1000 * 60 * 60));
  
  if (ageHours > 24) {
    console.log(`🚨 ALERT: Latest backup is ${ageHours} hours old!`);
    return;
  }
  
  // Check if backup file is empty
  if (latestBackup.size === 0) {
    console.log('🚨 ALERT: Latest backup file is empty!');
    return;
  }
  
  console.log('✅ No alerts - backups are up to date');
}

// Handle command line arguments
const args = process.argv.slice(2);

if (args.length === 0) {
  console.log('Usage:');
  console.log('  node monitor-backups.js status  - Check backup status');
  console.log('  node monitor-backups.js alert   - Send alert if backup is missing or failed');
  process.exit(1);
}

const command = args[0];

switch (command) {
  case 'status':
    checkBackupStatus();
    break;
  case 'alert':
    sendAlert();
    break;
  default:
    console.error(`Unknown command: ${command}`);
    process.exit(1);
}